package moe.server;

import java.io.IOException;

import moe.config.Configuration;
import moe.config.Constants;
import moe.config.PropertiesUtil;
import moe.util.Base64;

import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

public class HttpAuthenticateInterceptor implements HttpRequestInterceptor {

	public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
		authenticate(request, (HttpResponse) context.getAttribute(ExecutionContext.HTTP_RESPONSE));
	}

	private void authenticate(HttpRequest request, HttpResponse response) {
		if (!PropertiesUtil.hasProperty(Constants.HTTP_USER)) {
			return;
		}
		if (request.containsHeader(HttpHeaders.AUTHORIZATION)) {
			String auth = request.getFirstHeader(HttpHeaders.AUTHORIZATION).getValue();
			if (auth.contains(" ")) {
				auth = auth.split(" ")[1];
			}
			String user = Configuration.getHttpUser();
			String password = Configuration.getHttpPassword();
			if (auth.equals(Base64.encode(user + ":" + password))) {
				return;
			}
		}

		response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"MoeServer\"");
		response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
	}
}
